package com.sky.service.impl;



import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sky.config.AlipayConfig;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author dongdong 抖音号：W13883155245
 * @version 1.0
 * @date 2025/9/25
 * @description
 */

@Service
public class AlipayServiceImpl implements AlipayService {

    // 模拟数据库存储订单
    private static final Map<String, Orders> orderMap = new ConcurrentHashMap<>();

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public String payment(OrdersPaymentDTO ordersPaymentDTO) throws AlipayApiException {


        Long userId = BaseContext.getCurrentId();
        Orders order = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());


        // 保存订单到"数据库"
        orderMap.put(ordersPaymentDTO.getOrderNumber(), order);

        // 初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getPublicKey(),
                alipayConfig.getSignType()
        );

        // 创建支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());

        // 组装请求参数
        String outTradeNo = order.getNumber();
        String totalAmount = order.getAmount().toString();
        String subject = order.getUserName()+"点餐";
        String body = "用户id" + userId+"订单描述:"+order.getRemark();
        totalAmount="0.01";
        String bizContent = "{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"" +subject + "\"," +
                "\"body\":\"" + body + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                "}";

        alipayRequest.setBizContent(bizContent);

        // 调用支付宝接口，生成支付表单
        return alipayClient.pageExecute(alipayRequest).getBody();
    }


    @Override
    public String handleNotify(String outTradeNo, String tradeStatus, String tradeNo) {
        Orders order = orderMap.get(outTradeNo);
        if (order == null) {
            return "fail";
        }

        // 根据支付宝通知的交易状态更新订单
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            order.setStatus(5);
            order.setPayStatus(1);
            order.setCheckoutTime(LocalDateTime.now());
            order.setRemark(tradeNo);//todo 暂时放到备注里
            orderMap.put(outTradeNo, order);
            return "success";
        } else if ("TRADE_CLOSED".equals(tradeStatus) || "TRADE_FAILED".equals(tradeStatus)) {
            order.setStatus(1);
            order.setRejectionReason("支付失败: " + tradeStatus);
            orderMap.put(outTradeNo, order);
        }

        return "fail";
    }


}
